from django.contrib import admin
from django import urls as urlresolvers
from django.conf import settings
from django.urls.exceptions import NoReverseMatch
from django.utils.html import format_html

from auditlog.models import LogEntry, LoginEvent
from auditlog.mixins import LogEntryAdminMixin
from auditlog.filters import ResourceTypeFilter


class ReadOnlyPermission:
    def has_delete_permission(self, request, obj=None):
        return True if request.user.is_superuser else False

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False


class LogEntryAdmin(ReadOnlyPermission, admin.ModelAdmin, LogEntryAdminMixin):
    list_display = ['id', 'resource_url', 'action', 'msg_short', 'user_url', 'remote_addr', 'created']
    search_fields = ['timestamp', 'object_repr', 'changes', 'actor__first_name', 'actor__last_name']
    list_filter = ['action', ResourceTypeFilter]
    ordering = ['-id']
    readonly_fields = ['created', 'resource_url', 'action', 'user_url', 'msg']
    fieldsets = [
        (None, {'fields': ['created', 'user_url', 'remote_addr', 'resource_url']}),
        ('Changes', {'fields': ['action', 'msg']}),
    ]


admin.site.register(LogEntry, LogEntryAdmin)


@admin.register(LoginEvent)
class LoginEventAdmin(ReadOnlyPermission, admin.ModelAdmin):
    list_display = ('username', 'user_url', 'action', 'remote_ip', 'created')
    list_filter = ['action', 'user', 'created']
    ordering = ('-created', 'action', 'username')
    search_fields = ['=remote_ip', 'username', ]
    readonly_fields = ['action', 'username', 'user', 'remote_ip', 'created', ]

    def user_url(self, obj):
        if obj.user:
            app_label, model = settings.AUTH_USER_MODEL.split('.')
            viewname = 'admin:%s_%s_change' % (app_label, model.lower())
            try:
                link = urlresolvers.reverse(viewname, args=[obj.user.pk])
            except NoReverseMatch:
                return u'%s' % (obj.user)
            return format_html(u'<a href="{}">{}</a>', link, obj.user)

        return obj.username

    user_url.short_description = '用户名'

    def action(self, obj):
        return obj.get_action_display()

    action.short_description = '行为'
